
package com.mk.ancientrpcstarter.util;

import com.mk.ancientrpcstarter.logging.Log;
import com.mk.ancientrpcstarter.logging.LogFactory;
import com.mk.ancientrpcstarter.protocol.RpcProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @description:
 * @author: M.K
 * @date: 2021/11/17
 */

public class PkgDecoder extends ByteToMessageDecoder
{
    private Log log = LogFactory.getLog(PkgDecoder.class);

    public PkgDecoder(){ }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception
    {
        if (buffer.readableBytes() < RpcProtocol.HEAD_LEN) {
            return; // 未读完足够的字节流，缓存后继续读
        }

        byte[] intBuf = new byte[4];
        buffer.getBytes(buffer.readerIndex() + RpcProtocol.HEAD_LEN - 4, intBuf);
        int bodyLen = ByteConverter.bytesToIntBigEndian(intBuf);

        if (buffer.readableBytes() < RpcProtocol.HEAD_LEN + bodyLen) {
            return; // 未读完足够的字节流，缓存后继续读
        }

        byte[] bytesReady = new byte[RpcProtocol.HEAD_LEN + bodyLen];
        buffer.readBytes(bytesReady);
        out.add(bytesReady);
    }
}
